package com.my.ads.lib.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.my.ads.lib.Config;
import com.my.ads.lib.activity.MemoryBoostActivity;
import com.my.ads.lib.utils.Utils;

/**
 * Created by xuanyang on 2018/3/23.
 */

public class LockScreenReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {

        Log.i(Config.TagLog, "lock");
//        intent.getAction().equals(Intent.ACTION_SCREEN_ON) ||
        if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) { // 出现通知栏 开屏后直接广告

            Long now = System.currentTimeMillis();

            SharedPreferences sp = context.getSharedPreferences("preferences", context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();

            Long notificationTime = sp.getLong("NotificationTime", 0L);
            if (Math.abs(now - notificationTime) > 60 * 60 * 1000) {
                editor.putLong("NotificationTime", now);
                editor.apply();
                Utils.sendNotification(context);
            }

            Long memoryBoostTime = sp.getLong("MemoryBoostTime", 0L);
            if (TextUtils.isEmpty(Config.CurrentVersionName) || (Math.abs(now - memoryBoostTime) > 1000 * 30 && Utils.getVersionName(context).equals(Config.CurrentVersionName))) {
                Log.i(Config.TagLog, "lock memory boost");
                Utils.setCurrentVersionName(context);
                editor.putLong("MemoryBoostTime", now);
                editor.apply();
                Utils.startActivity(context.getApplicationContext(), MemoryBoostActivity.class);
            }

        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {

            if (!TextUtils.isEmpty(Config.CurrentVersionName) && Integer.valueOf(Utils.getVersionName(context).replace(".", "")) < Integer.valueOf(Config.CurrentVersionName.replace(".", ""))) {
                Log.i(Config.TagLog, "OFF " + Config.CurrentVersionName);
                Intent lockIntent = new Intent(Config.LockScreenAction);
                lockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                context.startActivity(lockIntent);
            } else {
                Log.i(Config.TagLog, "else " + Config.CurrentVersionName);
            }
        }
    }
}
